import roleApi from '@/api/auth/roleApi.js'
import utils from '@/common/utils.js'
import eMenuSelector from '@/components/menuSelector'
import userApi from '@/api/auth/userApi'
import {menuGroup} from '@/view/auth/dict'
import treeTools from "@/common/treeTools";

export default {
  name: "Role",
  components: {eMenuSelector},
  filters: {},
  data() {
    return {
      // 是否可见
      formVisible: false,
      // 表单标题
      formTitle: '',
      // 表单状态 edit,insert
      formState: '',
      // 保存事件是否完成,避免表单重复提交
      formLoading: false,
      // 表单数据
      formData: {
        id: '',
        name: '',
      },
      // 详情是否可见...
      detailVisible: false,
      // 详情数据
      detailData: {},
      // 查询项配置
      searchConf: [
        {
          label: '角色名',
          prop: 'name',
          type: 'input'
        },
      ],
      // 表格配置
      tableConf: {
        multiple: true,
        operateWidth: '200px',
        columns: [
          {
            label: '角色名',
            prop: 'name',
          },
        ]
      },
      // 按钮配置
      buttons: [
        {label: "详情", event: "detail", type: "primary", isLink: true},
      ],
      // 表单验证规则
      rules: {
        name: [{required: true, message: "请输入角色名", trigger: "blur"}],
      },
      currentRow: {},
      menuTree: {
        data: {},
        // leaves: [],
        loading: false,
        selectedKeys: {},
        props: {
          label: 'name',
          children: 'children',
          currentIds: [],
        },
        hasFetchTree: false,
      },
      options: {
        orgMap: {},
        menuGroup,
      }
    }
  },
  methods: {
    // 初始化 下拉数据的获取等
    init() {
    },
    listMenuTree() {
      return new Promise((resolve, reject) => {
          if (!this.menuTree.hasFetchTree) {
            userApi.listMenuTree().then(res => {
              this.options.menuGroup.list.forEach(menuGroup => {
                let menus = res.data
                let targetMenus = menus.find(e => e.group === menuGroup.value)
                if (targetMenus) {
                  this.$set(this.menuTree.data, menuGroup.value, targetMenus.menuTrees)
                }
              })
              this.hasFetchTree = true
              resolve()
            }).catch(err => {
              console.error(err);
              reject()
            }).finally(_ => {
            })
          }else{
            resolve()
          }
      })
    },
    // 菜单树节点选中变化事件
    handleMenuCheckChange() {
    },
    // 菜单树复选框点击事件
    handleMenuCheck(data, {checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys}) {
    },
    // 菜单树重置
    menuReset() {
      if (this.$refs.menuTree) {
        this.$refs.menuTree.forEach(tree => {
          tree.setCheckedKeys([])
        })
      }
    },
    // 获取列表数据
    setData(params, callback) {
      this.$rq.query(roleApi.url, params).then(res => {
        callback({total: res.data.total, data: res.data.rows})
      }).catch(err => {
        console.error(err)
      })
    },
    // 获取表格数据
    page() {
      this.$refs.page.getData()
    },
// 重置表格查询
    reset() {
      this.$refs.page.reset()
    },
    // 清空表单
    formClear() {
      if (this.$refs.menuSelector) {
        this.$refs.menuSelector.reset()
      }
      // 清空校验
      if (this.$refs.form) {
        this.$refs.form.clearValidate()
        this.$refs.form.resetFields()
      }
      // 重新赋值
      this.formData = {
        id: '',
        name: '',
      }
      this.menuReset()
    },
    // 保存事件
    formSave() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.formLoading = true
          let data = this.formParse(utils.formatObj(this.formData))
          if (this.formState === 'insert') {
            this.$rq.insert(roleApi.url, data).then(res => {
              this.$message.success('保存成功')
              this.hasFetchTree = false
              this.formVisible = false
              this.formLoading = false
              this.page()
            }, err => {
              this.formLoading = false
            })
          } else if (this.formState === 'edit') {
            this.$rq.updateById(roleApi.url, data).then(res => {
              this.$message.success('保存成功')
              this.hasFetchTree = false
              this.formVisible = false
              this.formLoading = false
              this.page()
            }, err => {
              this.formLoading = false
            })
          }
        }
      })
    },
    // 数据传到后端前需要做的操作
    formParse(formData) {
      let _formData = JSON.parse(JSON.stringify(formData))
      _formData.resources = []
      this.$refs.menuTree.forEach(tree => {
        _formData.resources.push(...tree.getCheckedKeys(), ...tree.getHalfCheckedKeys())
      })
      return _formData
    },
    // 表单关闭
    formClose() {
      this.formVisible = false
    },
    // 设置表单数据
    formSet(data) {
      this.formData.id = data.id
      this.formData.name = data.name
    },
    // 删除方法
    del({selection}) {
      if (selection.length) {
        let ids = selection.map(e => e.id)
        this.$confirm('确认删除?', {
          title: '提示',
          confirmButtonText: '删除',
          type: 'warning',
          callback: (action) => {
            if (action == 'confirm') {
              this.$rq.deleteByIds(roleApi.url, ids).then(res => {
                this.$message.success('删除成功')
                this.hasFetchTree = false
                this.page()
              })
            }
          }
        })
      } else {
        this.$message.warning('请至少选择一行')
      }
    },
    // 编辑
    edit({row}) {
      this.formClear()
      this.listMenuTree().then(_ => {
        roleApi.listMenuId({roleId: row.id}).then(res => {
          this.fosrmTitle = '编辑'
          this.formState = 'edit'
          this.formSet(row)
          this.formVisible = true
          this.$nextTick(_ => {
            menuGroup.list.forEach((e, index) => {
              let leaves = treeTools.getLeaves(this.menuTree.data[e.value])
              this.$refs.menuTree[index].setCheckedKeys(res.data.filter(e => ~leaves.indexOf(e)))
            })
          })
        })
      })
    },
    // 新增
    insert({row}) {
      this.listMenuTree().then(_ => {
        this.formTitle = '新增'
        this.formState = 'insert'
        this.formClear()
        this.formVisible = true
      })
    },
    // 详情
    detail({row}) {
      this.detailVisible = true
      this.detailData = row
    },
    // 关闭详情
    detailClose() {
      this.detailVisible = false
    },
    // ePage中的操作按钮,会相应的触发其event对应的事件
    handleEvent(event, payload, callback) {
      if (payload.row) {
        this.currentRow = payload.row
      }
      if (this[event] instanceof Function) {
        this[event](payload);
      } else {
        // this.$message.warning('按钮无效')
      }
    },
  },
  mounted() {
    this.page()
  },
  created() {
    this.init()
  }

};
